const router = require('koa-router')();
const mysql = require('mysql')
const WorkLog = require('../entity/WorkLog')

router.prefix('/workLog');

//获取url请求客户端ip

var getIp = function(req) {
    var ip = req.headers['x-real-ip'] ||
        req.headers['x-forwarded-for'] ||
        req.socket.remoteAddress || '';
    if(ip.split(',').length>0){
        ip = ip.split(',')[0];
    }
    return ip;
};
 

router.get('/index', async (ctx) => {
    try {
        const ipMap = require('../bin/ipMap')
        const ip = getIp(ctx.req)
        console.log(`访问者 ip: ${ip}`)
        if (ipMap[ip]) {
            await ctx.render('index', {
                title: 'work-log'
            })
        } else {
            await ctx.render('error', {
                title: 'error',
                message: '非法访问者',
                error: {
                    status: '401'
                }
            })  
        }
    } catch (error) {
        await ctx.render('error', {
            title: 'error',
            message: '非法访问者',
            error: {
                status: '401'
            }
        })  
    }
})

/*
    api
        /workLog/createDirectory    :创建目录/文件
        /workLog/logs               :拉去用户目录结构, 前端自行组织目录关系
        /workLog/readOrWriteFile    :读写单个文件
        /workLog/delDirectory       :删除接口
*/

/*
    创建目录/文件
    	"userid": "",   // 用户id
        "name": "a2",   // 文件 | 目录名
        "type": 0,      // 0 文件, 1 目录
        "pathParentId": "" // 上级目录 uuid
*/
router.post('/delDirectory', async (ctx) => {
    const { uuid } = ctx.request.body;
    let sql = mysql.format(`DELETE FROM work_log where uuid=?`,[uuid]);
    try {
        let res = await ctx.dbQuery(sql)
        console.log(res)
        ctx.body = {
            errorCode: 0,
            message: 'ok'
        }
    } catch (error) {
        ctx.body = {
            errorCode: 502,
            error
        }
    }
})
router.post('/createDirectory', async (ctx) => {
    const { name, pathParentId, userid, type } = ctx.request.body;

    let workLog = new WorkLog({ type, name, pathParentId, userid })
    let sql = mysql.format(`select * from work_log where userid=? and name=?`, [userid, name])
    if (type === '0') {
        // 文件
        sql = mysql.format(`select * from work_log where
            userid=? and
            name=? and
            type=? and
            path_parent_id=?`, [userid, name, type, pathParentId]
        )
    } else {
        // 目录
        sql = mysql.format(`select * from work_log where
            userid=? and
            type=? and
            name=?`, [userid, type, name]
        )
    }
    try {
        let res = await ctx.dbQuery(sql)
        if (res && res.results && res.results.length === 0) {
            let result = await workLog.submit(ctx.dbQuery, ctx.rootConfig.pathRoot)
            if (result.results.affectedRows === 1) {
                ctx.body = {
                    errorCode: 0,
                    message: 'ok'
                }
            } else {
                ctx.body = {
                    errorCode: -1,
                    result
                }
            }
        } else {
            ctx.body = {
                errorCode: 1,
                message: '已存在相同目录'
            }
        }
    } catch (error) {
        ctx.body = {
            errorCode: 502,
            message: '数据操作异常',
            error
        }
    }
})

/*
    拉去用户目录结构, 前端自行组织
*/
router.post('/logs', async (ctx) => {
    const { userid } = ctx.request.body
    let sql = mysql.format(`SELECT * from work_log WHERE userid=?`, [userid])
    let result = await ctx.dbQuery(sql)
    try {
        ctx.body = {
            errorCode: 0,
            result
        }
    } catch (error) {
        ctx.body = {
            errorCode: 502,
            error
        }
    }
})

/*
    写入|读取 单个文件
*/
router.post('/readOrWriteFile', async (ctx) => {
    const { uuid, type, text } = ctx.request.body;
    let workLog = new WorkLog({ uuid, text });
    try {
        let fileInfo = await workLog.readOrWriteFile(ctx.dbQuery, ctx.rootConfig.pathRoot, type);
        ctx.body = {
            errorCode: 0,
            fileInfo
        }
    } catch (error) {
        ctx.body = {
            errorCode: 502,
            error
        }
    }
})

module.exports = router;
